import React, {Component} from 'react'
import {View, Text, ActivityIndicator, StyleSheet,TouchableOpacity, ScrollView} from 'react-native'
import {
    GetAnswerApi, 
    PutRetractNewHomeworkApi,
    PostAnswerApi, 
    PutRetractAnswerApi, 
    PostTeacherReplyApi, 
    PutRetractReplyApi
} from '../../config/api'

import AttachmentManager from '../common/attachment_manager'
import {connect} from 'react-redux'
import StudentHomework from './student_homework'
import HeadingLine from '../common/heading_line'
import ContentLine from '../common/content_line'
import Enumeration from '../../config/enumeration'
import LoadingCommon from '../common/loading_common'
import styles,{BLUE} from '../../config/styles'

class HomeworkShow extends Component {
    
    static navigationOptions = ({ navigation }) => {
        const {params} = navigation.state
        if (params.name != undefined) {
            return {
                title: `${navigation.state.params.name}的作业`,
                headerRight: (<View />)
            }
        } else {
            return {title: '作业'}
        }
    }

    constructor (props) {
        super(props)
        const params = props.navigation.state.params
        this.state = {
            loading: true,
            id: params.id,
            homework: {},
            answers: [],
            backKey: params.key || 0,
            refresh: params.refresh,
            //如果是学生，用自己的ID，如果是老师，用props.studentid
            studentid: props.user.user.role == Enumeration.User.Role.Student ? props.user.user.id : params.studentid,
            submitting: false,
            content: "",
            attachments: []
        }
    }

    //获取homework
    get_homework () {
        GetAnswerApi(this.state.id, this.state.studentid).then((data) => {
            if (data.code === 0) {
                this.setState({
                    homework: data.homework,
                    answers: data.answers,
                    loading: false
                })             
            }
        })
    }


    recallBtnDisplay = () => {
        if(this.state.homework.answerno>0 || this.state.homework.replyno>0){
            return null;
        } else {
            return (<TouchableOpacity
                disabled={this.state.submitting}
                style={[styles.as_large_button,{marginTop:20}]}
                onPress={this.recallHomework}
            >
                <View>
                    <Text style={[styles.text_white]}>
                        {this.state.submitting ? '提交中...' : '撤回'}
                    </Text>
                </View>
            </TouchableOpacity>);
        }
    }

    //撤回作业
    recallHomework = () => {
        const {refresh, backKey} = this.state
        this.setState({
            submitting:true
        }, () => {
            PutRetractNewHomeworkApi(this.state.homework.id).then((data) => {
                if (data.code == 0) {
                    Toast.show('撤回成功')
                    this.props.navigation.goBack(backKey)
                    refresh()
                } else {
                    Toast.show('撤回失败')
                }
                this.setState({submitting: false})
            })
        })
    }

    
    componentWillMount () {
        this.get_homework()
    }

    render () {
        if (this.state.loading) {
            return (<LoadingCommon />)
        } else {
            const recallDisplay = this.recallBtnDisplay();
            const homework = this.state.homework
            const column_objects = [
                {name: '标题:', column: 'title'},
                {name: '课本:', column: 'textbook'}, 
                {name: '章节:', column: 'chapter'},
                {name: '内容:', column: 'description'}
            ]
            const role = this.props.user.user.role //2是学生， 1和3是老师         
            return (
                <ScrollView keyboardShouldPersistTaps={'always'} style={styles.scroll_view_container}>
                    <HeadingLine title={'作业名称'} color={BLUE} style={{backgroundColor: 'white'}} contentStyle={{backgroundColor: 'white'}} >
                        {column_objects.map((object, index) => {
                            return (
                                <ContentLine
                                    key={index} 
                                    name={object.name} 
                                    content={homework[object.column]} 
                                    bold={object.name == '标题:'}
                                />
                            )
                        })}
                        <ContentLine name={'附件:'} />
                        <View style={{flexDirection: 'row'}}>
                            <AttachmentManager
                                attachments={homework.attachments} 
                                navigation={this.props.navigation} 
                            />
                        </View>
                        <ContentLine name={'截止时间:'} content={'无'} />
                    </HeadingLine>
                    
                    {
                        this.state.studentid == undefined ?
                            recallDisplay :
                        this.state.answers.map((answer, index) => {
                            return (
                                    <StudentHomework
                                        key={index} 
                                        answer={answer} 
                                        role={role}
                                        homework_id={this.state.id}
                                        homework_status={this.state.homework.status}
                                        isLastAnswer={answer.id == this.state.homework.lastest_answer_id}
                                        isLastReply={answer.reply && answer.reply.id == this.state.homework.lastest_reply_id}
                                    />
                                )
                        })
                    }
                </ScrollView>
                
            )
        }
    }
}

const mapStateToProps = (state) => {
    return {
        user: state.user
    }
}

export default connect(mapStateToProps)(HomeworkShow)